/**
 *@描述：插入内部链接组件，其中包括知识列表
 *@作者：殷健
 *@创建时间：2022/7/7
 *@最后修改时间：2022/7/7
 */

import {Space, Modal, Input, List, PaginationProps, Pagination, Checkbox, Button} from 'antd';
import {LinkOutlined, SearchOutlined} from "@ant-design/icons";
import {useEffect, useState} from "react";
import {KnowledgeSearchRequest} from "@/pages/Dashboard/Knowledge/service";
import {CheckboxChangeEvent} from "antd/es/checkbox";
import {useModel} from "@@/plugin-model/useModel";
const InternalLinkModal = (
    {
        show,
        onSelect,
        onCancel,
    }:{
        show: boolean;
        onSelect?: (val: any) => void;
        onCancel?: () => void;
    }
) => {

    return (
        <Modal
            title={
                <Space>
                    <LinkOutlined />
                    知识列表
                </Space>
            }
            visible={show}
            centered
            destroyOnClose={true}
            footer={false}
            bodyStyle={{ padding: 10}}
            onCancel={onCancel}
            width={700}
        >
            <InternalLink onSelect={onSelect}></InternalLink>

        </Modal>
    )

}

//插入内部链接列表组件
//todo: 插入内部链接列表组件
const InternalLink = (
    {
        onSelect
    }:{
        onSelect?:(val:any)=>void;
    }
) => {

    //todo: 设置组件状态
    const [ loading,setLoading ] = useState(false);
    const [ pageSize ] = useState("5");
    const [ currentPage,setCurrentPage ] = useState("1");
    const [total, setTotal] = useState("0");
    const [authorId,setAuthorId] = useState("");
    const [sreachValue,setSreachValue] = useState("");
    const [ list,setList ] = useState<any[]>([]);
    const { initialState } = useModel('@@initialState');

    //组件初始化函数
    //todo: useEffect
    useEffect(()=>{
        // @ts-ignore
        gatKnowledgeSearch(sreachValue);
    },[currentPage])

    //分页-点击页码触发
    //todo:onChange
    const onChange: PaginationProps['onChange'] = page => {
        setCurrentPage(page.toString());
    };

    //知识列表查询，可根据关键字和是否仅限本人作品等参数查询
    //todo: gatKnowledgeSearch
    const gatKnowledgeSearch = async (
        {
            keyword
        }:{
            keyword?:string;
    }) => {
        setLoading(true);

        const requestParams: AircasKB.Knowledge.KnowledgeSearchRequestParams={
            knowledgeId:'11',
            authorId:authorId,
            currentPage:currentPage,
            pageSize:pageSize,
            keyword:keyword,
        }
        // console.log(requestParams);
        const res:AircasKB.ResponseType<AircasKB.Knowledge.KnowledgeSearchResponse> = await KnowledgeSearchRequest(requestParams)
        if(res.code== 200){
            const result:any=[];
            // @ts-ignore
            if(res.data.list.length>0){
                res.data.list?.map((item)=>{
                    let auther:string="";
                    const authorNames = item.authorNames;
                    // @ts-ignore
                    for(let i=0;i<authorNames?.length;i++){
                        auther+=authorNames?.[i].toString()+',';
                    }
                    auther+='等'+item.authorNames?.length+'人';
                    result.push({
                        id:item.id,
                        title:item.title,
                        author:auther,
                    })
                })
            }
            setList(result);
            // @ts-ignore
            setTotal(res.data.total);
        }
        setLoading(false);
    }

    //点击仅限本人作品复选框时触发，用于设置本人作品状态
    //todo: onCheckChange
    const onCheckChange = (e: CheckboxChangeEvent) => {
        if(e.target.checked){
            // @ts-ignore
            setAuthorId(initialState.currentUser?.id);
        }
        else{
            setAuthorId("");
        }
        console.log(`checked = ${e.target.checked}`);
    };

    return (
        <div>
            <List
                itemLayout="horizontal"
                dataSource={list || []}
                loading = {loading}
                header={
                    <div>
                        <Input
                            placeholder="请输入关键字"
                            style={{ width: 270 }}
                            onChange={(e)=>setSreachValue(e.target.value)}
                        ></Input>&nbsp;&nbsp;&nbsp;&nbsp;
                        <Checkbox onChange={onCheckChange}>限本人作品</Checkbox>
                        <Button
                            size="large"
                            type="primary"
                            icon={<SearchOutlined />}
                            style={{ marginLeft: 10 }}
                            onClick={async ()=>{
                                await gatKnowledgeSearch({
                                    keyword:sreachValue,
                                })
                            }}
                        >
                            搜索
                        </Button>
                    </div>
                }
                footer={
                    <Pagination showQuickJumper current={Number(currentPage)||1} pageSize={Number(pageSize) || 5} total={Number(total)||0} onChange={onChange}/>
                }
                bordered
                rowKey="id"
                renderItem={item => (
                    <List.Item>
                        <List.Item.Meta
                            title={<a onClick={() => onSelect?.(item)}>{item.title}</a>}
                            description={`作者：${item.author}`}
                        />
                    </List.Item>
                )}
            />
        </div>

    )
}
export default InternalLink;
export { InternalLinkModal };


